import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
import 'OneClass.dart';


class searchBarDelegate extends SearchDelegate<String>{
  @override
  String get searchFieldLabel => "搜索你想要的教室😉";

  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return IconButton(
      icon: AnimatedIcon(
        icon:AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () {
        if(query.isEmpty){
          close(context, null);
        }
        else{
          query = "";
          showSuggestions(context);
        }
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    // TODO: implement buildResults
    return query.length >0 ? FutureBuilder(
      future: getData(query),
      builder: (context, snapshot){
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('');
          case ConnectionState.active:
          case ConnectionState.waiting:
            return Text('');
          case ConnectionState.done:
            if (snapshot.hasError)
              return Text('');
            return Data.length >0 ? ListView.builder(
              padding: new EdgeInsets.all(5.0),
              itemExtent: 200.0,
              itemBuilder: (context, index){
                return Card(
                  elevation: 15.0,
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
                  child: Column(
                    children: [
                      ListTile(
                        title: Text('${Data[index]["BuildName"]} ${Data[index]["Class"]}'),
                        leading: Icon(
                          Icons.school,
                          color: Colors.blue,
                        ),
                        trailing: Icon(
                          Icons.arrow_forward_ios,
                        ),
                        onTap: (){
                          Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => OneClassPage(Data[index]["BuildName"], Data[index]["Class"])));
                        },
                      ),
                      Divider(),
                      ListTile(
                        title: Text('当前人数:${Data[index]["Num"]}  最大人数:${Data[index]["MaxNum"]}'),
                        leading: Icon(
                          Icons.people,
                          color: Colors.blue,
                        ),
                      ),
                      ListTile(
                        title: Text('百分比:${Data[index]["Percentage"]}%'),
                        leading: Icon(
                          Icons.more_vert,
                        ),
                      )
                    ],
                  ),
                );
              },
              itemCount: Data.length,
            )
                :
            Container(
              alignment: Alignment.center,
              child: Container(
                child: Text(
                    '没有相关数据😥',
                    style: TextStyle(
                      fontSize: 16,
                    )),
              ),
            );
        }
        return null; // unreachable
      },
    )
        :
    Text("");
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    // TODO: implement buildSuggestions
    return query != "" ? FutureBuilder(
      future: getData(query),
      builder: (context, snapshot){
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('');
          case ConnectionState.active:
          case ConnectionState.waiting:
            return Text('');
          case ConnectionState.done:
            if (snapshot.hasError)
              return Text('');
            return ListView.builder(
              padding: new EdgeInsets.all(5.0),
              itemExtent: 50.0,
              itemBuilder: (context, index){
                return ListTile(
                  onTap: (){
                    query = Data[index]["BuildName"] + " " + Data[index]["Class"];
                    showResults(context);
                  },
                  title: RichText(
                    text: TextSpan(
                      text: Data[index]["BuildName"] + Data[index]["Class"],
                      style: TextStyle(
                          color: Colors.black, fontWeight: FontWeight.bold),
                    ),
                  ),
                );
              },
              itemCount: Data.length,
            );
        }
        return null; // unreachable
      },
    ):
        Text("");
  }

  var KeyWord_confirm = List();
  var KeyWord_unconfirm = List();
  var Data = List();

  String MakeUrl(){
    if(this.KeyWord_confirm.length == 0 && this.KeyWord_unconfirm.length == 0){
      return '';
    }
    else{
//      print(KeyWord_confirm);
//      print(KeyWord_unconfirm);
      String url = 'https://www.fjnu-study.cn/request/inf_request.php?type=Search&key=';

      for(int i = 0;i < this.KeyWord_confirm.length;i++){
        if(i != 0){
          url = url + '@@';
        }
        url = url + this.KeyWord_confirm[i];
      }
      url = url + '^^';
//      print(url);
      return url;
    }
  }

  void GetKey(String SearchData){
    if(KeyWord_confirm.isNotEmpty){
      KeyWord_confirm.clear();
    }
    if(KeyWord_unconfirm.isNotEmpty){
      KeyWord_unconfirm.clear();
    }

    RegExp reg_Build = RegExp(r"[\u4e00-\u9fa5]{2}");
    RegExp reg_Class = RegExp(r"[0-9]-[0-9]{1,3}");
    RegExp reg_Class2 = RegExp(r"[0-9]{1,3}");

    if(reg_Build.hasMatch(SearchData)){
      Iterable<Match> matches = reg_Build.allMatches(SearchData);
      for(Match m in matches){
        String OneKey = m.group(0);
        if(OneKey != ""){
          this.KeyWord_confirm.add(OneKey);
        }
      }
    }

    if(reg_Class.hasMatch(SearchData)){
      Iterable<Match> matches = reg_Class.allMatches(SearchData);
      for(Match m in matches){
        String OneKey = m.group(0);
        if(OneKey != ""){
          this.KeyWord_confirm.add(OneKey);
        }
      }
    }
    else if(reg_Class2.hasMatch(SearchData)){
      Iterable<Match> matches = reg_Class2.allMatches(SearchData);
      for(Match m in matches){
        String OneKey = m.group(0);
        if(OneKey != ""){
          this.KeyWord_confirm.add(OneKey);
        }
      }
    }

    if(!reg_Build.hasMatch(SearchData) && !reg_Class.hasMatch(SearchData) && !reg_Class2.hasMatch(SearchData)){
      if(SearchData != ""){
        this.KeyWord_confirm.add(SearchData);
      }
    }
  }

  Future getData(SearchData) async{
    GetKey(SearchData);
    var url = MakeUrl();
    if(url != ''){
      var response = await http.get(url);
      if(response.statusCode == 200){
        var jsonRes = convert.jsonDecode(response.body);
        this.Data = jsonRes['Result'];
        NameTransform();
//        print("json:${this.Data}");
//        print(this.Data.length);
        return true;
      }
      else{
        print('数据请求失败!错误代码${response.statusCode}');
        return false;
      }
    }
    else{
      return false;
    }
  }

  void NameTransform(){
    if(this.Data.length > 0){
      for(var i = 0;i < this.Data.length;i++){
        switch(this.Data[i]['BuildName']){
          case 'ZM':{
            this.Data[i]['BuildName'] = '知明';
          }break;
          case 'XD':{
            this.Data[i]['BuildName'] = '笃行';
          }break;
          case 'LC':{
            this.Data[i]['BuildName'] = '立诚';
          }break;
          case 'ZG':{
            this.Data[i]['BuildName'] = '致广';
          }break;
        }
      }
    }
  }

}

//class SearchResult extends StatefulWidget{
//  var SearchData;
//  SearchResult(this.SearchData ,{Key key}):super(key:key);
//  _SearchResultState createState() => _SearchResultState(this.SearchData);
//}
//
//class _SearchResultState extends State<SearchResult>{
//  var SearchData;
//  var Data = List();
//  var KeyWord_confirm = List();
//  var KeyWord_unconfirm = List();
//
//  _SearchResultState(this.SearchData){
//    GetKey();
//  }
//
//  @override
//  void initState() {
//    // TODO: implement initState
//    super.initState();
//    getData();
//  }
//
//  @override
//  Widget build(BuildContext context) {
//    // TODO: implement build
//    return this.Data.isNotEmpty ?
//        ListView.builder(
//          padding: new EdgeInsets.all(5.0),
//          itemExtent: 200.0,
//          itemBuilder: (context, index){
//            return this.Data.length != 0 ?
//            CreateCard(
//                this.Data[index]['BuildName'],
//                this.Data[index]['Class'],
//                this.Data[index]['MaxNum'],
//                this.Data[index]['Num'],
//                this.Data[index]['Percentage'])
//                :
//              InitialCard();
//              },
//              itemCount: Data.length,
//        )
//        :
//      Container(
//        alignment: Alignment.center,
//        child: Container(
//          child: Text(
//            '没有相关数据😥',
//            style: TextStyle(
//              fontSize: 16,
//            )),
//        ),
//      );
//  }
//
//  Widget CreateCard(String BuildName, String ClassName, int MaxNum, int Num, var Percentage){
//    return Card(
//      elevation: 15.0,
//      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
//      child: Column(
//        children: [
//          ListTile(
//              title: Text('${BuildName} ${ClassName}'),
//              leading: Icon(
//                Icons.school,
//                color: Colors.blue,
//              ),
//              trailing: Icon(
//                Icons.arrow_forward_ios,
//              ),
//              onTap: (){
//                Navigator.push(
//                  context,
//                  MaterialPageRoute(builder: (context) => OneClassPage(BuildName, ClassName)));
//              },
//          ),
//          Divider(),
//          ListTile(
//            title: Text('当前人数:${Num}  最大人数:${MaxNum}'),
//            leading: Icon(
//              Icons.people,
//              color: Colors.blue,
//            ),
//          ),
//          ListTile(
//            title: Text('百分比:${Percentage}%'),
//            leading: Icon(
//              Icons.more_vert,
//            ),
//          )
//        ],
//      ),
//    );
//  }
//
//  Widget InitialCard(){
//    return Card(
//      elevation: 15.0,
//      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
//      child: Column(
//        children: [
//          ListTile(
//              title: Text('请刷新~'),
//              leading: Icon(
//                Icons.school,
//                color: Colors.blue,
//              )
//          ),
//          Divider(),
//          ListTile(
//            title: Text(''),
//            leading: Icon(
//              Icons.people,
//              color: Colors.blue,
//            ),
//          ),
//          ListTile(
//            title: Text('百分比: %'),
//            leading: Icon(
//              Icons.more_vert,
//            ),
//          )
//        ],
//      ),
//    );
//  }
//
//  String MakeUrl(){
//    if(this.KeyWord_confirm.length == 0 && this.KeyWord_unconfirm.length == 0){
//      return '';
//    }
//    else{
//      String url = 'http://101.132.226.81/bklx/inf_request?type=Search&key=';
//
//      for(int i = 0;i < this.KeyWord_confirm.length;i++){
//        if(i != 0){
//          url = url + '@@';
//        }
//        url = url + this.KeyWord_confirm[i];
//      }
//      url = url + '^^';
//      for(int i = 0;i < this.KeyWord_unconfirm.length;i++){
//        if(i != 0){
//          url = url + '@@';
//          url = url + this.KeyWord_unconfirm[i];
//        }
//      }
//      print(url);
//      return url;
//    }
//  }
//
//  void GetKey(){
//    RegExp reg_Build = RegExp(r"[\u4e00-\u9fa5]{2}");
//    RegExp reg_Class = RegExp(r"[0-9]-[0-9]{1,3}");
//    RegExp reg_Class2 = RegExp(r"[0-9]{1,3}");
//
//    if(reg_Build.hasMatch(this.SearchData)){
//      Iterable<Match> matches = reg_Build.allMatches(this.SearchData);
//      for(Match m in matches){
//        String OneKey = m.group(0);
//        if(OneKey != ""){
//          this.KeyWord_confirm.add(OneKey);
//        }
//      }
//    }
//
//    if(reg_Class.hasMatch(this.SearchData)){
//      Iterable<Match> matches = reg_Class.allMatches(this.SearchData);
//      for(Match m in matches){
//        String OneKey = m.group(0);
//        if(OneKey != ""){
//          this.KeyWord_confirm.add(OneKey);
//        }
//      }
//    }
//    else if(reg_Class2.hasMatch(this.SearchData)){
//      Iterable<Match> matches = reg_Class2.allMatches(this.SearchData);
//      for(Match m in matches){
//        String OneKey = m.group(0);
//        if(OneKey != ""){
//          this.KeyWord_confirm.add(OneKey);
//        }
//      }
//    }
//
//    if(!reg_Build.hasMatch(this.SearchData) && !reg_Class.hasMatch(this.SearchData) && !reg_Class2.hasMatch(this.SearchData)){
//      if(this.SearchData != ""){
//        this.KeyWord_unconfirm.add(this.SearchData);
//      }
//    }
//  }
//
//  Future getData() async{
//    var url = MakeUrl();
//    if(url != ''){
//      var response = await http.get(url);
//      if(response.statusCode == 200){
//        var jsonRes = convert.jsonDecode(response.body);
//        setState(() {
//          this.Data = jsonRes['Result'];
//          NameTransform();
//          print(this.Data);
//        });
//        return true;
//      }
//      else{
//        print('数据请求失败!错误代码${response.statusCode}');
//        return false;
//      }
//    }
//    else{
//      return false;
//    }
//  }
//
//  void NameTransform(){
//    if(this.Data.length > 0){
//      for(var i = 0;i < this.Data.length;i++){
//        switch(this.Data[i]['BuildName']){
//          case 'ZM':{
//            this.Data[i]['BuildName'] = '知明';
//          }break;
//          case 'XD':{
//            this.Data[i]['BuildName'] = '笃行';
//          }break;
//          case 'LC':{
//            this.Data[i]['BuildName'] = '立诚';
//          }break;
//          case 'ZG':{
//            this.Data[i]['BuildName'] = '致广';
//          }break;
//        }
//      }
//    }
//  }
//}
